package com.liziing.controller;

import com.google.gson.Gson;
import com.liziing.dto.ClassroomInfoReqDTo;
import com.liziing.dto.ClassroomRespDTO;
import com.liziing.dto.ClassroomStatusReqDTO;
import com.liziing.mapper.ClassRoomMapper;
import com.liziing.pojo.ClassRoom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@SuppressWarnings("all")  //取消所有预警
@RequestMapping("classroom")
@CrossOrigin(origins = {"*", "null"})  //解决跨域
public class ClassRoomController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ClassRoomMapper classRoomMapper;

    private Gson gson = new Gson();

    @GetMapping("/getList")
    public String getClassRoom() {
        String classroom = stringRedisTemplate.opsForValue().get("classroom");
        if (stringRedisTemplate.opsForValue().get("classroom") != null) {
            return classroom;
        }
        List<ClassRoom> classRooms = classRoomMapper.selectList(null);
        stringRedisTemplate.opsForValue().set("classroom",  gson.toJson(classRooms));
        return gson.toJson(classRooms);
    }

    @PostMapping("/update")
    public void updateClassRoom(@RequestBody ClassRoom classRoom) {
        System.out.println(classRoom);
        classRoomMapper.updateById(classRoom);
        stringRedisTemplate.delete("classroom");
    }

    @PostMapping("/delete")
    public void deleteClassRoom(@RequestBody ClassRoom classRoom) {
        classRoomMapper.deleteById(classRoom);
        stringRedisTemplate.delete("classroom");
    }

    @PostMapping("/add")
    public void addClassRoom(@RequestBody ClassRoom classRoom) {
        classRoomMapper.insert(classRoom);
        stringRedisTemplate.delete("classroom");
    }

    @PostMapping("/search")
    public String searchByType(@RequestBody ClassroomStatusReqDTO classRoom) {
        //查询出筛选出的结果
        List<ClassRoom> classRooms = classRoomMapper.search(classRoom);

        return gson.toJson(classRooms);
    }
    @GetMapping("searchAvgInfo")
    public String searchAvgInfo() {
        ClassroomRespDTO classroomRespDTO = classRoomMapper.searchAvgInfo();
        return gson.toJson(classroomRespDTO);
    }

    @PostMapping("getClassroomInfo")
    public String getClassroomInfo(@RequestBody String classroomId) {
        ClassroomInfoReqDTo classroomInfo = classRoomMapper.getClassroomInfo(classroomId);
        return gson.toJson(classroomInfo);
    }
}
